<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="发布人" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入发布人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['square:square:add']"
          v-if="isParent"
        >我要发布家教</el-button>
      </el-col>
      <el-col :span="1.5">
        <!-- <el-button
          type="text"
          icon="el-icon-check"
          size="mini"
          :disabled="single || selectedStatus === 'approved'"
          @click="handleUpdate"
          v-hasPermi="['square:square:edit']"
          class="accept-order-btn"
          v-if="isTeacher"
        >我要接单</el-button> -->
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['square:square:remove']"
          v-if="isAdmin"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <!-- <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['square:square:export']"
        >导出</el-button> -->
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="squareList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="requestId" sortable/>
      <el-table-column label="内容" align="center" prop="content" />
      <el-table-column label="发布人" align="center" prop="name" v-if="isTeacher || isAdmin" />
      <el-table-column label="发布人手机" align="center" prop="phoneNumber" v-if="isTeacher || isAdmin" />
      <el-table-column 
        label="发布时间" 
        align="center" 
        prop="creatTime" 
        width="180"
        v-if="isTeacher || isAdmin"
        sortable
        :sort-orders="['ascending', 'descending']"
        @sort-change="handleSortChange('creatTime')"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.creatTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.order_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="接单人" align="center" prop="teacherName" v-if="isParent || isAdmin" />
      <el-table-column label="接单人手机" align="center" prop="teacherContact" v-if="isParent || isAdmin" />
      <el-table-column 
  label="接单时间" 
  align="center" 
  prop="acceptedTime" 
  width="180"
  v-if="isParent || isAdmin"
  sortable
  :sort-orders="['ascending', 'descending']"
  @sort-change="handleSortChange('acceptedTime')"
>
  <template slot-scope="scope">
    <span>{{ parseTime(scope.row.acceptedTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
  </template>
</el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="isTeacher">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['square:square:edit']"
            :disabled="scope.row.status !== 'pending'"
            class="accept-order-btn"
            v-show="showAcceptOrderBtn"
          >我要接单</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['square:square:remove']"
          >删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改家教广场对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="内容" prop="content">
          <el-input v-model="form.content" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <!-- <el-form-item label="发布人" prop="name">
          <el-input v-model="form.name" placeholder="请输入发布人" />
        </el-form-item> -->
        <!-- <el-form-item label="发布人手机" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入发布人手机" />
        </el-form-item> -->
        <!-- <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.order_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>

      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSquare, getSquare, delSquare, addSquare, updateSquare } from "@/api/square/square";
import { addMy_requests, listMy_requests, updateMy_requests } from "@/api/my_requests/my_requests";
import { addApplication, getApplicationByUserId } from "@/api/application/application";

export default {
  name: "Square",
  dicts: ['order_status'],
  computed: {
    isTeacher() {
      return localStorage.getItem("roleName") === "教员";
    },
    isParent() {
      return localStorage.getItem("roleName") === "家长";
    },
    isAdmin() {
      return localStorage.getItem("roleName") === "超级管理员";
    }
  },
  data() {
    return {
      showAcceptOrderBtn: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 选中行的状态
      selectedStatus: '',
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 家教广场表格数据
      squareList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        content: null,
        name: null,
        status: null,
              orderByColumn: null, // 排序字段
      isAsc: null          // 排序方向
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        content: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ],
        name: [
          // { required: true, message: "发布人不能为空", trigger: "blur" }
        ],
        phoneNumber: [
          // { required: true, message: "发布人手机不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.checkApplicationStatus();
  },

  methods: {
    checkApplicationStatus() {
      const roleName = localStorage.getItem("roleName");
      if (roleName == '教员') {
        getApplicationByUserId(localStorage.getItem("userId")).then(response => {
          // console.log("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
          // console.log(response);

          if (response.status == 'approved') {
            console.log("您已通过教员认证，可以接单");
            this.$modal.msgSuccess("您是平台认证的教员，可以接单");
            
            this.showAcceptOrderBtn = true;
          }else{
            this.$modal.msgWarning("您尚未通过教员认证，无法接单");
          }
        });
      }
    },
    /** 查询家教广场列表 */
    getList() {
      this.loading = true;
      // console.log('this.queryParams',this.queryParams);
      listSquare(this.queryParams).then(response => {
        this.squareList = response.rows;
        // console.log('11111111111',this.squareList);

        this.total = response.total;
        this.loading = false;
      });
    },
    /** 排序触发事件 */
  handleSortChange(column) {
    return (sort) => {
      if (sort.prop === column) {
        this.queryParams.orderByColumn = column;
        this.queryParams.isAsc = sort.order === 'ascending' ? 'asc' : 'desc';
        this.getList();
      }
    };
  },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        requestId: null,
        content: null,
        name: null,
        phoneNumber: null,
        creatTime: null,
        status: 'pending',
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.requestId)
      this.single = selection.length!==1
      this.multiple = !selection.length
      this.selectedStatus = selection.length === 1 ? selection[0].status : ''
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "发布家教";
      // 从本地存储获取家长姓名和电话
      this.form.name = localStorage.getItem("userName");
      this.form.phoneNumber = localStorage.getItem("parentPhoneNumber");
    },
    /** 接单按钮操作（原修改按钮） */
    handleUpdate(row) {
      if (row.status === 'approved') {
        this.$modal.msgWarning("该订单已被接单，无法再次接单。");
        return;
      }
      const that = this;
      this.$modal.confirm('您确定要接单吗？接单后请保证服务质量', '确认接单', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'el-button--primary',
        cancelButtonClass: 'el-button--default',
        customClass: 'custom-modal',
        buttonsStyling: false,
        showConfirmButton: true,
        showCancelButton: true,
        type: 'warning',
        center: true,
        roundButton: true,
        distinguishCancelAndClose: true
      }).then(function() {
        // 更新订单状态为 'approved'
        const orderData = {
          ...row,
          status: 'approved',
          teacherName: localStorage.getItem("userName"),
          teacherContact: localStorage.getItem("teacherPhoneNumber"),
          acceptedTime: new Date().toISOString().slice(0, 19).replace('T', ' ') // 格式化为 'yyyy-MM-dd HH:mm:ss'
        };

        updateSquare(orderData).then(response => {
          console.log('家教广场更新成功，开始查找对应的发布记录');
          console.log('查询参数:', {
            parentName: row.name,
            parentPhoneNumber: row.phoneNumber,
            requestContent: row.content,
            requestPostedTime: row.creatTime
          });
          that.$modal.msgSuccess("您已成功接单！");
          that.getList(); // 刷新数据
        }).catch(error => {
          that.$modal.msgError("接单失败，请重试。");
        });
      }).catch(() => { });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 确保 requestId 是数字
          if (this.form.requestId != null) {
            this.form.requestId = Number(this.form.requestId); // 转换为数字
            console.log('requestId:', this.form.requestId, '类型:', typeof this.form.requestId);
            updateSquare(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              this.$modal.msgError("更新失败，请重试。");
            });
          } else {
            // 设置发布时间为当前时间，格式化为 yyyy-MM-dd HH:mm:ss
            const now = new Date();
            this.form.creatTime = now.getFullYear() + '-' +
              String(now.getMonth() + 1).padStart(2, '0') + '-' +
              String(now.getDate()).padStart(2, '0') + ' ' +
              String(now.getHours()).padStart(2, '0') + ':' +
              String(now.getMinutes()).padStart(2, '0') + ':' +
              String(now.getSeconds()).padStart(2, '0');

            addSquare(this.form).then(response => {
              // 同步数据到我的发布
              const myRequestData = {
                parentName: this.form.name,
                parentPhoneNumber: this.form.phoneNumber,
                requestContent: this.form.content,
                requestPostedTime: this.form.creatTime,  // 使用带时分秒的时间
                requestStatus: this.form.status,
                // teacherName: this.form.teacherName,
                // teacherPhoneNumber: this.form.teacherContact,
                // requestAcceptedTime: this.form.acceptedTime
              };

              addMy_requests(myRequestData).then(response => {
                this.$modal.msgSuccess("发布成功，数据已同步到我的发布");
                this.open = false;
                this.getList();
              }).catch(error => {
                this.$modal.msgError("数据同步到我的发布失败");
              });
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const requestIds = Number(row.requestId || this.ids);
      this.$modal.confirm('是否确认删除家教广场编号为"' + requestIds + '"的数据项？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'el-button--primary',
        cancelButtonClass: 'el-button--default',
        customClass: 'custom-modal',
        buttonsStyling: false,
        showConfirmButton: true,
        showCancelButton: true,
        type: 'warning',
        center: true,
        roundButton: true,
        distinguishCancelAndClose: true
      }).then(function() {
        return delSquare(requestIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('square/square/export', {
        ...this.queryParams
      }, `square_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.accept-order-btn {
  background-color: #f4f0ff;
  color: #6c5ce7;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
}

.accept-order-btn:hover:not([disabled]) {
  background-color: #6c5ce7;
  color: white;
}

.accept-order-btn[disabled] {
  background-color: #f5f7fa;
  color: #c0c4cc;
  cursor: not-allowed;
}

/* 移除el-button type="text"的默认样式 */
.accept-order-btn.el-button--text {
  background-color: #f4f0ff;
  padding: 8px 16px;
}

.accept-order-btn.el-button--text:hover:not([disabled]) {
  background-color: #6c5ce7;
  color: white;
}

/* 弹窗按钮样式 */
:global(.custom-modal .el-message-box__btns) {
  display: flex;
  flex-direction: row-reverse;
  justify-content: center;
}

:global(.custom-modal .el-message-box__btns button) {
  margin-left: 10px;
}

:global(.custom-modal .el-message-box__btns button:first-child) {
  margin-left: 0;
  order: 2;
}

:global(.custom-modal .el-message-box__btns button:last-child) {
  margin-right: 0;
  order: 1;
}

/* 排序按钮样式 */
.el-table .sort-caret {
  width: 0;
  height: 0;
  border: 5px solid transparent;
  position: absolute;
}

.el-table .ascending .sort-caret.ascending {
  border-bottom-color: #409EFF;
}

.el-table .descending .sort-caret.descending {
  border-top-color: #409EFF;
}
</style>

<style scoped>
.app-container {
  padding: 30px;
  min-height: 100vh;
  background: linear-gradient(135deg, #f6f8fc 0%, #f1f4f9 100%);
}

.app-container .el-form {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  padding: 25px;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);
  border: 1px solid rgba(255, 255, 255, 0.8);
  margin-bottom: 25px;
}

.app-container .el-form .el-form-item {
  margin-bottom: 0;
  margin-right: 20px;
}

.app-container .el-form .el-form-item .el-input__inner,
.app-container .el-form .el-form-item .el-select .el-input__inner {
  border-radius: 8px;
  border-color: #dcdfe6;
  transition: all 0.3s ease;
}

.app-container .el-form .el-form-item .el-input__inner:hover,
.app-container .el-form .el-form-item .el-input__inner:focus,
.app-container .el-form .el-form-item .el-select .el-input__inner:hover,
.app-container .el-form .el-form-item .el-select .el-input__inner:focus {
  border-color: #e61e1e;
}

.app-container .el-form .el-button {
  padding: 8px 20px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.app-container .el-form .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.app-container .mb8 {
  margin-bottom: 25px;
}

.app-container .mb8 .el-button {
  padding: 10px 20px;
  border-radius: 8px;
  transition: all 0.3s ease;
  font-weight: 500;
}

.app-container .mb8 .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.app-container .mb8 .el-button.el-button--primary {
  background: linear-gradient(135deg, #e61e1e, #ff6b6b);
  border: none;
}

.app-container .mb8 .el-button.el-button--primary:hover {
  background: linear-gradient(135deg, #ff6b6b, #e61e1e);
}

.app-container .el-table {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);
  border: 1px solid rgba(255, 255, 255, 0.8);
  margin-bottom: 25px;
}

.app-container .el-table::before {
  display: none;
}

.app-container .el-table .el-table__header-wrapper th {
  background: rgba(230, 30, 30, 0.05);
  color: #2c3e50;
  font-weight: 600;
  padding: 15px 0;
}

.app-container .el-table .el-table__body-wrapper td {
  padding: 15px 0;
  color: #606266;
}

.app-container .el-table .el-button {
  padding: 6px 12px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.app-container .el-table .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.app-container .el-table .el-button.el-button--danger {
  background: linear-gradient(135deg, #ff4d4f, #ff7875);
  border: none;
}

.app-container .el-table .el-button.el-button--danger:hover {
  background: linear-gradient(135deg, #ff7875, #ff4d4f);
}

.app-container .el-pagination {
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  padding: 20px;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);
  border: 1px solid rgba(255, 255, 255, 0.8);
  text-align: center;
}

.app-container .el-pagination .el-pagination__total,
.app-container .el-pagination .el-pagination__jump {
  color: #606266;
}

.app-container .el-pagination .btn-prev,
.app-container .el-pagination .btn-next,
.app-container .el-pagination .el-pager li {
  background: transparent;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.app-container .el-pagination .btn-prev:hover,
.app-container .el-pagination .btn-next:hover,
.app-container .el-pagination .el-pager li:hover {
  color: #e61e1e;
  border-color: #e61e1e;
}

.app-container .el-pagination .btn-prev.active,
.app-container .el-pagination .btn-next.active,
.app-container .el-pagination .el-pager li.active {
  background: #e61e1e;
  color: white;
  border-color: #e61e1e;
}

.app-container .el-dialog {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.app-container .el-dialog .el-dialog__header {
  background: linear-gradient(135deg, #e61e1e, #ff6b6b);
  padding: 20px;
  margin: 0;
}

.app-container .el-dialog .el-dialog__header .el-dialog__title {
  color: white;
  font-size: 18px;
  font-weight: 600;
}

.app-container .el-dialog .el-dialog__header .el-dialog__headerbtn {
  top: 20px;
}

.app-container .el-dialog .el-dialog__header .el-dialog__headerbtn .el-icon-close {
  color: white;
}

.app-container .el-dialog .el-dialog__body {
  padding: 30px;
}

.app-container .el-dialog .el-dialog__body .el-form-item__label {
  font-weight: 500;
  color: #2c3e50;
}

.app-container .el-dialog .el-dialog__body .el-input__inner,
.app-container .el-dialog .el-dialog__body .el-textarea__inner {
  border-radius: 8px;
  border-color: #dcdfe6;
  transition: all 0.3s ease;
}

.app-container .el-dialog .el-dialog__body .el-input__inner:hover,
.app-container .el-dialog .el-dialog__body .el-input__inner:focus,
.app-container .el-dialog .el-dialog__body .el-textarea__inner:hover,
.app-container .el-dialog .el-dialog__body .el-textarea__inner:focus {
  border-color: #e61e1e;
}

.app-container .el-dialog .el-dialog__footer {
  padding: 20px 30px;
  border-top: 1px solid #ebeef5;
}

.app-container .el-dialog .el-dialog__footer .el-button {
  padding: 10px 25px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.app-container .el-dialog .el-dialog__footer .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

@media screen and (max-width: 768px) {
  .app-container {
    padding: 20px;
  }

  .app-container .el-form {
    padding: 15px;
  }

  .app-container .el-form .el-form-item {
    margin-right: 10px;
  }

  .app-container .el-table .el-table__header-wrapper th,
  .app-container .el-table .el-table__body-wrapper td {
    padding: 10px 0;
  }
}
</style>
